package com.lmt;

import com.google.gson.Gson;
import com.google.gson.JsonIOException;
import feign.FeignException;
import feign.Response;
import feign.codec.DecodeException;
import feign.codec.Decoder;

import java.io.IOException;
import java.lang.reflect.Type;

/**
 * Date 2018/06/28
 *
 * @author MT-Lin
 */
public class GsonDecoder implements Decoder {

    private final Gson gson = new Gson();

    /*
     * (non-Javadoc)
     *
     * @see feign.codec.Decoder#decode(feign.Response, java.lang.reflect.Type)
     */
    @SuppressWarnings("DuplicateThrows")
    @Override
    public Object decode(Response response, Type type) throws IOException, DecodeException, FeignException {
        try {
            return gson.fromJson(response.body().asReader(), type);
        } catch (JsonIOException e) {
            if (e.getCause() != null && e.getCause() instanceof IOException) {
                throw IOException.class.cast(e.getCause());
            }
            throw e;
        }
    }

}
